package org.ww.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.ww.common.constant.RabbitMqConstant;
import org.ww.common.to.mq.OrderTo;
import org.ww.common.to.mq.SeckillOrderTo;
import org.ww.common.utils.PageUtils;
import org.ww.common.utils.Query;
import org.ww.common.utils.R;
import org.ww.common.utils.redis.RedisCache;
import org.ww.common.vo.MemberRespVo;
import org.ww.order.constant.PayConstant;
import org.ww.order.dao.OrderDao;
import org.ww.order.entity.OrderEntity;
import org.ww.order.entity.OrderItemEntity;
import org.ww.order.entity.PaymentInfoEntity;
import org.ww.order.feign.CartFeignService;
import org.ww.order.feign.MemberFeignService;
import org.ww.order.feign.ProductFeignService;
import org.ww.order.feign.WareFeignService;
import org.ww.order.interceptor.OrderLoginInterceptor;
import org.ww.order.service.OrderItemService;
import org.ww.order.service.OrderService;
import org.ww.order.service.PaymentInfoService;
import org.ww.order.to.OrderCreateTo;
import org.ww.order.to.SpuInfoVo;
import org.ww.order.vo.*;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static org.ww.order.constant.OrderConstant.USER_ORDER_TOKEN_PREFIX;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    ThreadLocal<OrderSubmitVo> orderSubmitVoThreadLocal = new InheritableThreadLocal<>();
    @Autowired
    private MemberFeignService memberFeignService;
    @Autowired
    private CartFeignService cartFeignService;
    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
    @Autowired
    private WareFeignService wareFeignService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private PaymentInfoService paymentInfoService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        MemberRespVo memberRespVo = OrderLoginInterceptor.loginUser.get();
        OrderConfirmVo confirmVo = new OrderConfirmVo();
        Long memberId = memberRespVo.getId();
        if(memberId == null){
            return null;
        }
        /**
         * 异步调用会造成不在同一线程内，导致其他线程无法获取ThreadLocal中的内容
         * 将requestAttributes在每一个线程中放一个
         */
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        //1、查询当前登录人的地址信息
        CompletableFuture<Void> addressFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);

            List<MemberAddressVo> address = memberFeignService.getAddress(memberId);
            confirmVo.setMemberAddressVos(address);
        }, threadPoolTaskExecutor);

        //2、查询购物车中所有被选中的商品
        CompletableFuture<Void> itemFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);

            List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
            confirmVo.setItems(currentUserCartItems);
        }, threadPoolTaskExecutor).thenRunAsync(() -> {
            List<OrderItemVo> items = confirmVo.getItems();
            List<Long> skuIds = items.stream().map(OrderItemVo::getSkuId).distinct().collect(Collectors.toList());
            R r = wareFeignService.hasstock(skuIds);
            List<SkuStockVo> skuStockVos = r.getData(new TypeReference<List<SkuStockVo>>() {
            });
            Map<Long, Boolean> skuStockMap = Optional.ofNullable(skuStockVos)
                    .orElseGet(ArrayList::new)
                    .stream()
                    .collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getIsStock));
            confirmVo.setStocks(skuStockMap);
        });


        //3、查询用户积分
        Integer integration = memberRespVo.getIntegration();
        confirmVo.setIntegration(integration);

        //4、其他数据自动计算

        //5、防重令牌
        String uuidToken = UUID.randomUUID().toString().replace("-", "");
        confirmVo.setOrderToken(uuidToken);
        redisCache.setCacheObject(USER_ORDER_TOKEN_PREFIX + memberId,uuidToken,30L, TimeUnit.MINUTES);

        //所有任务执行完成继续往下走
        CompletableFuture.allOf(addressFuture,itemFuture).get();

        return confirmVo;
    }

    /**
     * GlobalTransactional
     * 在高并发的场景下，不考虑使用AT模式的分布式事务（二阶段提交），主要是该事务会上来加很多锁，使得高并发变成个串行化
     * 考虑事务的最终一致性，保证数据在最后是一致的
     * 在下单锁库存的时候我们可以给消息队列发送锁成功的消息，然后订单只要支付成功，我们就进行扣库存，订单超时或者支付失败我们进队库存进行补偿
     * @param vo
     * @return
     */
//    @GlobalTransactional
    @Transactional(rollbackFor = Exception.class)
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        MemberRespVo memberRespVo = OrderLoginInterceptor.loginUser.get();
        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
        responseVo.setCode(0);

        String orderToken = vo.getOrderToken();
        if(!StringUtils.isEmpty(orderToken)){
            //下单，创建订单，验令牌，验价格，锁库存...

            //1、验证令牌，保存获取令牌、对比令牌和删除令牌是一个原子操作 采用lua脚本
            String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";

            //通过lure脚本原子验证令牌和删除令牌
            Long result = (Long) redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),
                    Arrays.asList("gmall:" + USER_ORDER_TOKEN_PREFIX + memberRespVo.getId()),
                    orderToken);
            if(result == 1L){
                //创建订单信息
                orderSubmitVoThreadLocal.set(vo);
                OrderCreateTo order = createOrder();
                //2、验证价格
                BigDecimal payAmount = order.getOrder().getPayAmount();
                BigDecimal payPrice = vo.getPayPrice();

                if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
                    //金额对比...
                    //...
                    //3、保存订单
                    saveOrder(order);
                    //4、锁定库存，只要有异常就回滚订单数据
                    WareSkuLockVo lockVo = new WareSkuLockVo();
                    lockVo.setOrderSn(order.getOrder().getOrderSn());
                    List<OrderItemVo> orderItemVos = order.getOrderItems().stream().map(item -> {
                        OrderItemVo itemVo = new OrderItemVo();
                        itemVo.setSkuId(item.getSkuId());
                        itemVo.setCount(item.getSkuQuantity());
                        itemVo.setTitle(item.getSkuName());
                        return itemVo;
                    }).collect(Collectors.toList());
                    lockVo.setLocks(orderItemVos);
                    /**
                     * 这里不用seata分布式事务，主要在高并发的情况下性能较差
                     * 采用mq + 最终一致性的方案
                     * 锁单成功之后向mq发送消息：
                     * 1、订单超时未支付或者用户取消之后对库存进行解锁
                     * 2、锁库存成功，但是后续业务出错，需要库存自动解锁
                     */
                    R r = wareFeignService.orderLockStock(lockVo);
                    if(r.getCode() == 0){
                        //锁成功了
                        responseVo.setOrder(order.getOrder());
                        //向订单队列中发送消息
                        rabbitTemplate.convertAndSend(RabbitMqConstant.ORDER_EVENT_EXCHANGE,RabbitMqConstant.ORDER_CREATE_ORDER_BINDING,order.getOrder());
//                        int i = 10/0;
                        return responseVo;
                    }else{
                        //锁定失败
                        responseVo.setCode(3);
                        return responseVo;
                    }

                }else{
                    responseVo.setCode(2);
                    return responseVo;
                }
            }else{
                //令牌验证失败
                responseVo.setCode(1);
            }
        }

        return responseVo;
    }

    @Override
    public OrderEntity getByOrderSn(String orderSn) {
        LambdaQueryWrapper<OrderEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(OrderEntity::getOrderSn,orderSn);
        return baseMapper.selectOne(wrapper);
    }

    /**
     * 一定时间内，用户未支付订单，执行取消订单逻辑
     * @param entity
     */
    @Override
    public void orderClose(OrderEntity entity) {
        //获取订单状态
        OrderEntity orderEntity = baseMapper.selectById(entity.getId());
        //如果订单状态为代付款，则取消订单
        if(orderEntity.getStatus().equals(OrderStatusEnum.CREATE_NEW.getCode())){
            OrderEntity updateOrder = new OrderEntity();
            updateOrder.setId(orderEntity.getId());
            updateOrder.setStatus(OrderStatusEnum.CANCLED.getCode());
            baseMapper.updateById(updateOrder);

            //为了防止订单超时未取消，导致库存锁定没有扣减，这里主动触发库存锁定扣减
            OrderTo to = new OrderTo();
            BeanUtils.copyProperties(orderEntity,to);
            try{
                rabbitTemplate.convertAndSend(RabbitMqConstant.ORDER_EVENT_EXCHANGE,"order.release.other",to);
            }catch (Exception e){
                /**
                 *  --------------消息丢失--------------
                 *  采用柔性事务（消息队列 + 最终一致性）的方案，最怕就是消息丢失的问题，为了防止消息丢失，可以采取如下措施
                 *  1、消息确认机制（生产端消息确认回调+消费端消息手动ack)
                 *  2、做好消息发送记录，定期扫描未发送成功的消息记录进行重试（表结构查看mq_message.sql）
                 *
                 *  --------------消息重复消费--------------
                 *  消息重复消费解决方案：
                 *  1、关键点在于业务是否是幂等的，比如库存服务，在订单超时解锁库存的时候会判断当前库存状态，需要将业务代码设置成幂等的
                 *  2、使用防重表，可以将消息的唯一id存入redis中，每次消费的时候判断当前id的消息是否被消费过了
                 *
                 *  --------------消息积压--------------
                 *  消息积压解决方案：
                 *  1、可以上线多个消费者
                 *  2、如果处理业务时间过长，可以将消息先取出来存入数据库里边，然后后续慢慢进行处理
                 *
                 */
            }
        }
    }

    @Override
    public PayVo getPayVo(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity orderEntity = this.getByOrderSn(orderSn);
        //获取商品信息
        List<OrderItemEntity> orderItemList = orderItemService.list(new LambdaQueryWrapper<OrderItemEntity>().eq(OrderItemEntity::getOrderSn, orderSn));
        OrderItemEntity orderItemEntity = orderItemList.get(0);

        payVo.setBody(orderItemEntity.getSkuName());
        payVo.setSubject(orderItemEntity.getSkuName());
        payVo.setOut_trade_no(orderSn);
        BigDecimal totalAmount = orderEntity.getTotalAmount().setScale(2, BigDecimal.ROUND_UP);
        payVo.setTotal_amount(totalAmount.toString());
        return payVo;
    }

    @Override
    public PageUtils listWithItem(Map<String, Object> params) {
        Long memberId = OrderLoginInterceptor.loginUser.get().getId();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
                        .eq("member_id",memberId)
                        .orderByDesc("id")
        );
        if(CollectionUtils.isNotEmpty(page.getRecords())){
            List<OrderEntity> records = page.getRecords();
            List<String> orderSnList = Optional.ofNullable(records)
                    .orElseGet(ArrayList::new)
                    .stream()
                    .map(OrderEntity::getOrderSn)
                    .distinct()
                    .collect(Collectors.toList());

            List<OrderItemEntity> orderItemEntities = orderItemService.list(new LambdaQueryWrapper<OrderItemEntity>().in(OrderItemEntity::getOrderSn, orderSnList));
            Map<String, List<OrderItemEntity>> orderItemMap = Optional.ofNullable(orderItemEntities)
                    .orElseGet(ArrayList::new)
                    .stream()
                    .collect(Collectors.groupingBy(OrderItemEntity::getOrderSn));
            Optional.ofNullable(records)
                    .orElseGet(ArrayList::new)
                    .forEach(r -> {
                        r.setItemEntities(orderItemMap.get(r.getOrderSn()));
                        }
                    );

        }

        return new PageUtils(page);
    }

    /**
     * 处理支付宝的支付结果
     * @param asyncVo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String handlePayResult(PayAsyncVo asyncVo) {

        //保存交易流水信息
        PaymentInfoEntity paymentInfo = new PaymentInfoEntity();
        paymentInfo.setOrderSn(asyncVo.getOut_trade_no());
        paymentInfo.setAlipayTradeNo(asyncVo.getTrade_no());
        paymentInfo.setTotalAmount(new BigDecimal(asyncVo.getBuyer_pay_amount()));
        paymentInfo.setSubject(asyncVo.getBody());
        paymentInfo.setPaymentStatus(asyncVo.getTrade_status());
        paymentInfo.setCreateTime(new Date());
        paymentInfo.setCallbackTime(asyncVo.getNotify_time());
        //添加到数据库中
        paymentInfoService.save(paymentInfo);

        //修改订单状态
        //获取当前状态
        String tradeStatus = asyncVo.getTrade_status();

        if (tradeStatus.equals("TRADE_SUCCESS") || tradeStatus.equals("TRADE_FINISHED")) {
            //支付成功状态
            String orderSn = asyncVo.getOut_trade_no(); //获取订单号
            this.updateOrderStatus(orderSn,OrderStatusEnum.PAYED.getCode(), PayConstant.ALIPAY);
        }

        return "success";
    }

    @Override
    public void createSeckillOrder(SeckillOrderTo orderTo) {
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderTo.getOrderSn());
        orderEntity.setMemberId(orderTo.getMemberId());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        BigDecimal payAmount = orderTo.getSeckillPrice().multiply(new BigDecimal(orderTo.getNum().toString()));
        orderEntity.setPayAmount(payAmount);
        this.save(orderEntity);

        //保存订单项信息 TODO:其他信息自补
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        orderItemEntity.setOrderSn(orderTo.getOrderSn());
        orderItemEntity.setRealAmount(payAmount);
        orderItemEntity.setSkuQuantity(orderTo.getNum());
        orderItemService.save(orderItemEntity);
    }


    /**
     * 修改订单状态
     * @param orderSn
     * @param code
     */
    private void updateOrderStatus(String orderSn, Integer code,Integer payType) {

        this.baseMapper.updateOrderStatus(orderSn,code,payType);
    }


    /**
     * 保存订单数据
     * @param order
     */
    private void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        baseMapper.insert(orderEntity);

        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItemService.saveBatch(orderItems);
    }

    private OrderCreateTo createOrder() {
        OrderCreateTo to = new OrderCreateTo();
        //生成订单号
        String orderSn = IdWorker.getTimeId();
        //获取订单信息
        OrderEntity orderEntity = builderOrder(orderSn);

        //获取所有订单项信息
        //2、获取到所有的订单项
        List<OrderItemEntity> orderItemEntities = builderOrderItems(orderSn);

        //3、验价(计算价格、积分等信息)
        computePrice(orderEntity,orderItemEntities);

        to.setOrder(orderEntity);
        to.setOrderItems(orderItemEntities);

        return to;
    }

    /**
     * 计算价格的方法
     * @param orderEntity
     * @param orderItemEntities
     */
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntities) {

        //总价
        BigDecimal total = new BigDecimal("0.0");
        //优惠价
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal intergration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");

        //积分、成长值
        Integer integrationTotal = 0;
        Integer growthTotal = 0;

        //订单总额，叠加每一个订单项的总额信息
        for (OrderItemEntity orderItem : orderItemEntities) {
            //优惠价格信息
            coupon = coupon.add(orderItem.getCouponAmount());
            promotion = promotion.add(orderItem.getPromotionAmount());
            intergration = intergration.add(orderItem.getIntegrationAmount());

            //总价
            total = total.add(orderItem.getRealAmount());

            //积分信息和成长值信息
            integrationTotal += orderItem.getGiftIntegration();
            growthTotal += orderItem.getGiftGrowth();

        }
        //1、订单价格相关的
        orderEntity.setTotalAmount(total);
        //设置应付总额(总额+运费)
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setCouponAmount(coupon);
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(intergration);

        //设置积分成长值信息
        orderEntity.setIntegration(integrationTotal);
        orderEntity.setGrowth(growthTotal);

        //设置删除状态(0-未删除，1-已删除)
        orderEntity.setDeleteStatus(0);

    }

    private OrderEntity builderOrder(String orderSn) {
        //获取当前用户登录信息
        MemberRespVo memberResponseVo = OrderLoginInterceptor.loginUser.get();

        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setMemberId(memberResponseVo.getId());
        orderEntity.setOrderSn(orderSn);
        orderEntity.setMemberUsername(memberResponseVo.getUsername());

        OrderSubmitVo orderSubmitVo = orderSubmitVoThreadLocal.get();

        //远程获取收货地址和运费信息
        R fareAddressVo = wareFeignService.getFare(orderSubmitVo.getAddrId());
        FareVo fareResp = fareAddressVo.getData("data", new TypeReference<FareVo>() {});

        //获取到运费信息
        BigDecimal fare = fareResp.getFare();
        orderEntity.setFreightAmount(fare);

        //获取到收货地址信息
        MemberAddressVo address = fareResp.getAddress();
        //设置收货人信息
        orderEntity.setReceiverName(address.getName());
        orderEntity.setReceiverPhone(address.getPhone());
        orderEntity.setReceiverPostCode(address.getPostCode());
        orderEntity.setReceiverProvince(address.getProvince());
        orderEntity.setReceiverCity(address.getCity());
        orderEntity.setReceiverRegion(address.getRegion());
        orderEntity.setReceiverDetailAddress(address.getDetailAddress());

        //设置订单相关的状态信息
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);
        orderEntity.setConfirmStatus(0);
        return orderEntity;
    }


    /**
     * 构建所有订单项数据
     * @return
     */
    public List<OrderItemEntity> builderOrderItems(String orderSn) {

        List<OrderItemEntity> orderItemEntityList = new ArrayList<>();

        //最后确定每个购物项的价格
        List<OrderItemVo> currentCartItems = cartFeignService.getCurrentUserCartItems();
        if (currentCartItems != null && currentCartItems.size() > 0) {
            orderItemEntityList = currentCartItems.stream().map((items) -> {
                //构建订单项数据
                OrderItemEntity orderItemEntity = builderOrderItem(items);
                orderItemEntity.setOrderSn(orderSn);

                return orderItemEntity;
            }).collect(Collectors.toList());
        }

        return orderItemEntityList;
    }

    /**
     * 构建某一个订单项的数据
     * @param items
     * @return
     */
    private OrderItemEntity builderOrderItem(OrderItemVo items) {

        OrderItemEntity orderItemEntity = new OrderItemEntity();

        //1、商品的spu信息
        Long skuId = items.getSkuId();
        //获取spu的信息
        R spuInfo = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo spuInfoData = spuInfo.getData("data", new TypeReference<SpuInfoVo>() {
        });
        orderItemEntity.setSpuId(spuInfoData.getId());
        orderItemEntity.setSpuName(spuInfoData.getSpuName());
        orderItemEntity.setSpuBrand(spuInfoData.getBrandName());
        orderItemEntity.setCategoryId(spuInfoData.getCatalogId());

        //2、商品的sku信息
        orderItemEntity.setSkuId(skuId);
        orderItemEntity.setSkuName(items.getTitle());
        orderItemEntity.setSkuPic(items.getImage());
        orderItemEntity.setSkuPrice(items.getPrice());
        orderItemEntity.setSkuQuantity(items.getCount());

        //使用StringUtils.collectionToDelimitedString将list集合转换为String  apache
        String skuAttrValues = StringUtils.collectionToDelimitedString(items.getSkuAttrValues(), ";");
        orderItemEntity.setSkuAttrsVals(skuAttrValues);

        //3、商品的优惠信息

        //4、商品的积分信息
        orderItemEntity.setGiftGrowth(items.getPrice().multiply(new BigDecimal(items.getCount())).intValue());
        orderItemEntity.setGiftIntegration(items.getPrice().multiply(new BigDecimal(items.getCount())).intValue());

        //5、订单项的价格信息
        orderItemEntity.setPromotionAmount(BigDecimal.ZERO);
        orderItemEntity.setCouponAmount(BigDecimal.ZERO);
        orderItemEntity.setIntegrationAmount(BigDecimal.ZERO);

        //当前订单项的实际金额.总额 - 各种优惠价格
        //原来的价格
        BigDecimal origin = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
        //原价减去优惠价得到最终的价格
        BigDecimal subtract = origin.subtract(orderItemEntity.getCouponAmount())
                .subtract(orderItemEntity.getPromotionAmount())
                .subtract(orderItemEntity.getIntegrationAmount());
        orderItemEntity.setRealAmount(subtract);

        return orderItemEntity;
    }

}